/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 驿站代收开通审核
 */
import React, { useRef, useCallback, useEffect, useState } from 'react';
import { getPullingBlackLog, blackListAdd, blackListDel } from '@/services/tools/blacklist';
import ProTable from '@ant-design/pro-table';
import { Input, Button, message, Popconfirm } from 'antd';
import { useSelector } from 'umi';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { TableListItem } from './index.d';
import type { ConnectState } from '@/models/connect';
import styles from './index.less';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';

interface RefuseModalProps {
  children: JSX.Element;
  tableRef: ActionType | undefined;
}

const RefuseModal: React.FC<RefuseModalProps> = ({ children, tableRef }) => {
  return (
    <ModalForm
      title='添加平台黑名单'
      trigger={children}
      width={480}
      onFinish={async (values) => {
        const { code, msg } = await blackListAdd(values);
        if (code == 0) {
          message.success(msg);
          tableRef?.reload();
          return true;
        }
        message.error(msg);
        return false;
      }}
    >
      <ProForm.Item>
        <ProFormText
          label='黑名单手机号'
          placeholder='请填写手机号'
          name='phone'
          rules={[{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确手机号' }]}
        />
        <ProFormText label='添加原因' name='remark' placeholder='请填写添加原因' />
      </ProForm.Item>
    </ModalForm>
  );
};

const BlackListTable = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const [platform, setPlatForm] = useState<string>('1');

  const cancelPullingBlack = async (item: TableListItem) => {
    const { id = '', table_name = '', black_phone = '' } = item;

    const params: {
      id: any;
      table_name: string;
      black_phone: string;
      platform: string;
    } = {
      id,
      platform,
    };
    if (platform == '3') {
      params.table_name = table_name;
      params.black_phone = black_phone;
    }

    const { code, msg } = await blackListDel(params);
    if (code == 0) {
      message.success(msg);
      actionRef?.current?.reload();
      return true;
    }
    message.error(msg);
    return false;
  };
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '选择平台',
      width: 150,
      dataIndex: 'channel',
      align: 'center',
      valueType: 'select',
      initialValue: '1',
      hideInTable: true,
      fieldProps: {
        options: [
          {
            label: '平台',
            value: '1',
          },
          {
            label: '智慧管理后台',
            value: '2',
          },
          {
            label: '驿站',
            value: '3',
          },
        ],
        allowClear: false,
        onChange: (_: string) => {
          setPlatForm(_);
        },
      },
    },
    {
      title: '手机号',
      hideInTable: true,
      dataIndex: 'search',
      hideInSearch: platform !== '3',
      renderFormItem: () => {
        return (
          <ProFormText
            placeholder='输入客户手机号或后四位（必填）'
            name='search'
            rules={[{ required: true, message: '输入客户手机号或后四位' }]}
          />
        );
      },
    },
    {
      title: '手机号',
      hideInTable: true,
      dataIndex: 'search',
      hideInSearch: platform == '3',
      renderFormItem: () => {
        return <Input name='search' allowClear placeholder='输入黑名单手机号或后四位' />;
      },
    },
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '拉黑手机号',
      dataIndex: 'black_phone',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '拉黑账号名称',
      dataIndex: 'blacked_by_name',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '拉黑账号',
      dataIndex: 'blacked_by_phone',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '添加原因',
      dataIndex: 'remark',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '拉黑时间',
      dataIndex: 'create_at',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '操作',
      align: 'center',
      key: 'option',
      width: winSize === 'xs' ? 90 : 130,
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => {
        return (
          <Popconfirm title='确定取消拉黑' onConfirm={cancelPullingBlack.bind(null, record)}>
            <a key='link'>移除黑名单</a>
          </Popconfirm>
        );
      },
    },
  ];

  const requestTableData = useCallback(async (values) => {
    const { current, pageSize, search, channel } = values;
    setPlatForm(channel);
    const reqData: {
      page: number;
      size: number;
      search: string;
      platform: string;
    } = {
      page: current,
      size: pageSize,
      search,
      platform: channel,
    };
    const { code, data, msg } = await getPullingBlackLog(reqData);
    if (code == 0) {
      return { data: data.data, total: data.count };
    } else {
      message.error(msg);
    }
  }, []);

  useEffect(() => {
    actionRef.current?.reload();
  }, []);

  return (
    <>
      <ProTable<TableListItem>
        actionRef={actionRef}
        rowKey='id'
        className={styles.table}
        request={requestTableData}
        columns={columns}
        options={false}
        expandable={{
          defaultExpandAllRows: false,
        }}
        pagination={{
          pageSize: 20,
          showQuickJumper: false,
          showSizeChanger: false,
        }}
        scroll={{ x: 1200 }}
        search={{
          optionRender: (_, { form }) => [
            <Button
              key='phone'
              type='primary'
              onClick={() => {
                form?.submit();
              }}
            >
              搜索
            </Button>,
            <RefuseModal key='refuse' tableRef={actionRef.current}>
              <Button key='phone' type='primary'>
                添加黑名单
              </Button>
            </RefuseModal>,
          ],
        }}
      />
    </>
  );
};

export default BlackListTable;
